package com.cqc.manage.service.Imp.business;

import cn.hutool.core.date.DateUtil;
import com.cqc.manage.dto.BusinessDto;
import com.cqc.manage.entity.Business;
import com.cqc.manage.entity.MessageBusiness;
import com.cqc.manage.repositories.BusinessRepositories;
import com.cqc.manage.repositories.MessageBusinessRepositories;
import com.cqc.manage.util.thrift.TTSocket;
import com.cqc.manage.util.thrift.ThriftClientConnectPoolFactory;
import javassist.runtime.Desc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.*;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Component
@EnableScheduling
@Configuration      //1.主要用于标记配置类，兼备Component的效果。
public class BusinessService {

    private Logger LOG = LoggerFactory.getLogger(BusinessService.class);

    @Autowired
    private BusinessRepositories businessRepositories;

    @Autowired
    private ThriftClientConnectPoolFactory thriftClientPool;

    @Autowired
    private MessageBusinessRepositories messageBusinessRepositories;


    public List<Business> getAllData(){
        List<Business> all = businessRepositories.findAll();
        return all;
    }

    /**
     * 每隔五分钟同步一次, MessageBusiness表
     * @return
     */
    @Scheduled(cron = "0 */20 * * * ?")
//    @Scheduled(cron = "0/5 * * * * ?")
    public void getAllBusiness(){
        List<String> contractNo = new ArrayList<>();
        TTSocket ttSocket = null;
        try {
            List<Business> businesses = new ArrayList<>();
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd") ;
            ttSocket = thriftClientPool.getConnect();

            List<Map<String, String>> businessList = ttSocket.getService().getBusinessList();
            LOG.info("thrift结果:{}",businessList.toString());
            LOG.info("thrift数据量:{}",businessList.stream().count());
            for(Map<String,String> map:businessList){
                Business business = new Business();
                business.setId(UUID.randomUUID().toString());
                business.setClient(map.get("委托单位"));
                business.setContractNo(map.get("合同编号"));
                business.setEngineer("");
                business.setReportType(map.get("报告类型"));
                business.setStandard(map.get("标准"));
                business.setEndDate(sdf1.parse(map.get("任务到期日期")));
                business.setStartDate(sdf1.parse(map.get("委托日期")));
                business.setSampleCategory(map.get("样品类别"));
                business.setSampleModel(map.get("样品型号"));
                businesses.add(business);
                business.setFlat(true);
                contractNo.add(business.getContractNo());
            }
            saveBusines(businesses);
            thriftClientPool.returnConnection(ttSocket);
            List<String> allByContractNo = businessRepositories.getAllContractNo();
            allByContractNo.removeAll(contractNo);
            for(String contractno:allByContractNo){
                Business byContractNo = businessRepositories.findByContractNo(contractno);
                byContractNo.setFlat(false);
                businessRepositories.save(byContractNo);
            }
        } catch (Exception e) {
            e.printStackTrace();
            thriftClientPool.invalidateObject(ttSocket);
        } finally {
//            thriftClient.close();
        }
    }

    public void getBusinessMessage(String contractNo) throws Exception {
        TTSocket ttSocket = null;

        try {
            ttSocket = thriftClientPool.getConnect();
            List<Map<String, String>> message = ttSocket.getService().getBusinvoice(contractNo);
            LOG.info("业务信息获取:{}",message);
            thriftClientPool.returnConnection(ttSocket);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    public void saveBusines(List<Business> businessList){
        for(Business business:businessList){
            try {
                Business byContractNo = businessRepositories.findByContractNo(business.getContractNo());
                if (byContractNo != null){
                    continue;
                }
                businessRepositories.save(business);
                LOG.info("新增业务：{}",business);
            }catch (Exception e ){
                System.err.println(business.toString());
            }

        }
    }


    /**
     * 分页查询
     * @param pageable
     * @return
     */
    public Page<Business> query(Pageable pageable){
//        getAllBusiness();
//        Specification<Business> specification = new Specification<Business>() {
//            @Override
//            public Predicate toPredicate(Root<Business> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
//
//                return null;
//            }
//        };
        Page<Business> all = businessRepositories.getAll(pageable);
        return all;
    }


    /**
     * 通过合同编号查询合同信息
     * @param businessDto
     */
    public void getBusiness(BusinessDto businessDto){
        MessageBusiness byContractNo = messageBusinessRepositories.findByContractNo(businessDto.getContractNo());
        if (byContractNo != null) {
            businessDto.setSampleModel(byContractNo.getSampleModel());
            businessDto.setStandard(byContractNo.getStandard());
            businessDto.setReportType(byContractNo.getReportType());
            businessDto.setSampleCategory(byContractNo.getSampleCategory());
            businessDto.setStartDate(DateUtil.format(byContractNo.getStartDate(), "yyyy-MM-dd"));
            businessDto.setEndDate(DateUtil.format(byContractNo.getEndDate(), "yyyy-MM-dd"));
            businessDto.setClient(byContractNo.getClient());
        }
    }

    /**
     *
     * @param contractNo  合同编号
     * @return
     */
    public BusinessDto getBusiness(String contractNo){
        MessageBusiness byContractNo = messageBusinessRepositories.findByContractNo(contractNo);
        BusinessDto businessDto = new BusinessDto();
        if (byContractNo != null) {
            businessDto.setContractNo(byContractNo.getContractNo());
            businessDto.setSampleModel(byContractNo.getSampleModel());
            businessDto.setStandard(byContractNo.getStandard());
            businessDto.setReportType(byContractNo.getReportType());
            businessDto.setSampleCategory(byContractNo.getSampleCategory());
            businessDto.setStartDate(DateUtil.format(byContractNo.getStartDate(), "yyyy-MM-dd"));
            businessDto.setEndDate(DateUtil.format(byContractNo.getEndDate(), "yyyy-MM-dd"));
            businessDto.setClient(byContractNo.getClient());

            return businessDto;
        }
        return null;

    }

    /**
     * 查询未完成的业务,并通过end_data排序
     */
    public Page<MessageBusiness>  getNoCompleteBussiness(String engName){
        Specification<MessageBusiness> specification = new Specification<MessageBusiness>() {
            @Override
            public Predicate toPredicate(Root<MessageBusiness> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                Predicate equal = criteriaBuilder.equal(root.get("engineer"), engName);
                query.where(criteriaBuilder.and(equal));
                query.orderBy(criteriaBuilder.desc(root.get("endDate")));
                return query.getRestriction();
            }
        };
        Page<MessageBusiness> all = messageBusinessRepositories.findAll(specification, PageRequest.of(1, 10));
        return all;
    }


}


